package com.web.util;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
 * Created by hxlc on 2016/12/28.
 */

/**
 * CSV数据下载
 */
public class FileOutputUtils {


    /** CSV文件列分隔符 */
    private static final String CSV_COLUMN_SEPARATOR_COMMA = ",";
    private static final String CSV_COLUMN_SEPARATOR_TABLE = "\t";
    /** CSV文件列分隔符 */
    private static final String CSV_RN = "\r\n";

    /**
     *
     * 将检索数据输出对应的csv列中
     * */
    public static String formatCsvData(List<Map<String, Object>> data) {

        StringBuffer buf = new StringBuffer();
        String CSV_COLUMN_SEPARATOR = "";
        CSV_COLUMN_SEPARATOR = CSV_COLUMN_SEPARATOR_COMMA;
        List<String> displayColNamesArr = new ArrayList<>();
        Map<String, Object> m = data.get(0);
        //列头

        for(String k:m.keySet()){
            displayColNamesArr.add(k);
        }

        for(int i=0;i<displayColNamesArr.size()-1;i++){
            buf.append(displayColNamesArr.get(i)).append(CSV_COLUMN_SEPARATOR);
        }
        buf.append(displayColNamesArr.get(displayColNamesArr.size()-1)).append(CSV_RN);

        //列值
        for(int i = 0;i<data.size();i++){
            for(int j=0;j<displayColNamesArr.size()-1;j++){
                buf.append(data.get(i).get(displayColNamesArr.get(j))).append(CSV_COLUMN_SEPARATOR);
            }
            buf.append(data.get(i).get(displayColNamesArr.get(displayColNamesArr.size()-1)));
            buf.append(CSV_RN);
        }
        return buf.toString();
    }

    public static String formatTxtData(List<Map<String, Object>> data) {
        StringBuffer buf = new StringBuffer();
        String CSV_COLUMN_SEPARATOR = "";
        CSV_COLUMN_SEPARATOR = CSV_COLUMN_SEPARATOR_TABLE;
        List<String> displayColNamesArr = new ArrayList<>();
        Map<String, Object> m = data.get(0);
        int length=20;
        //列头
        for(String k:m.keySet()){
            displayColNamesArr.add(k);
        }
        String t = "";
        for(int i=0;i<displayColNamesArr.size()-1;i++){
            t = appentStr4Length(displayColNamesArr.get(i),length);
            buf.append(t).append(CSV_COLUMN_SEPARATOR);
        }
        t= appentStr4Length(displayColNamesArr.get(displayColNamesArr.size()-1),length);
        buf.append(t).append(CSV_RN);

        //列值
        for(int i = 0;i<data.size();i++){
            for(int j=0;j<displayColNamesArr.size()-1;j++){
                t = appentStr4Length( data.get(i).get(displayColNamesArr.get(j)).toString(),length);
                buf.append(t).append(CSV_COLUMN_SEPARATOR);
            }
            t = appentStr4Length(  data.get(i).get(displayColNamesArr.get(displayColNamesArr.size()-1)).toString(),length) ;
            buf.append(t);
            buf.append(CSV_RN);
        }
        return buf.toString();
    }

    /**
     *
     * 将检索数据输出的数据转换成list类型
     * */
//    public static List<Object> StringToList(String listText) {
//        if (listText == null || listText.equals("")) {
//            return null;
//        }
//        listText = listText.substring(1);
//
//        listText = EspUtils.DecodeBase64(listText);
//
//        List<Object> list = new ArrayList<Object>();
//        String[] text = listText.split(SEP1);
//        for (String str : text) {
//            if (str.charAt(0) == 'M') {
//                Map<?, ?> map = StringToMap(str);
//                list.add(map);
//            } else if (str.charAt(0) == 'L') {
//                List<?> lists = StringToList(str);
//                list.add(lists);
//            } else {
//                list.add(str);
//            }
//        }
//        return list;
//    }
    /**
     * 文件下载
     */
    public static void outputStr(String strdata, HttpServletResponse response, String fileName){
        byte [] b=strdata.getBytes();
        try {

            byte[] buffer = strdata.getBytes("GBK");
            // 清空response
            response.reset();
            response.setStatus(200);
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" +java.net.URLEncoder.encode(fileName, "UTF-8"));
//    		             response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            // toClient.write(new String(new byte[] { (byte) 0xEF, (byte) 0xBB,(byte) 0xBF }));
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public static String appentStr4Length(String str , int length){
        if(str == null){
            str = "";
        }
        try {
            int strLen = 0;//计算原字符串所占长度,规定中文占两个,其他占一个
            for(int i = 0 ; i<str.length(); i++){
                if(isChinese(str.charAt(i))){
                    strLen = strLen + 2;
                }else{
                    strLen = strLen + 1;
                }
            }
            if(strLen>=length){
                return str;
            }
            int remain = length - strLen;//计算所需补充空格长度
            for(int i =0 ; i< remain ;i++){
                str =" " +  str;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return str;
    }

    private static boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION) {
            return true;
        }
        return false;
    }



}

